<?php

namespace App\Console\Commands\Cruise;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ImportConfigDB extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:import-config-db {url}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入本次cruise相关配置表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $url = $this->argument('url');
        $content = json_decode(file_get_contents($url), true);

        // id预检查
        foreach ($content as $table => $arr) {

            if (!$arr) {
                continue;
            }

            foreach ($arr as $val) {
                if (!isset($val['id'])) {
                    continue;
                }

                $ct = DB::table($table)->where('id', $val['id'])->count();
                if ($ct) {
                    dd("{$table} id:{$val['id']} 已存在，停止导入");
                }
            }
        }

        DB::beginTransaction();

        foreach ($content as $table => $arr) {

            if (!$arr) {
                continue;
            }

            DB::table($table)->insert($arr);
        }

        DB::commit();
    }
}
